package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;

    @Value("${leadnews.jwt.expire}")
    private Integer expire;
    @Autowired
    private WmUserMapper userMapper;

    @Override
    public ResponseResult<Map<String, Object>> login(WmLoginDto dto) {
        //数据校验
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //校验用户名和密码
        QueryWrapper<WmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",dto.getName());
        WmUser loginUser = getOne(queryWrapper);

        if(loginUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        if(!BCrypt.checkpw(dto.getPassword(),loginUser.getPassword())){
            throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR); //业务异常
        }

        //生成token给前端返回
        loginUser.setPassword(null);//在token不存储密码等敏感信息
        try {
            //读取私钥文件
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
            String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);

            Map<String,Object> result = new HashMap<>();
            result.put("token",token);
            result.put("user",loginUser);
            return ResponseResult.okResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e); //系统异常
        }
    }

    @Override
    public WmUser findByNewsId(Long articleId) {
        return userMapper.findByNewsId(articleId);
    }
}
